<template>
  <div>
    <Modal
        v-model="effectModel"
        title="测试定制化效果"
        :footer-hide="true"
        :width="900"
        class="codeForm"
        :mask-closable="false"
       >
        <div class="title">
          <span style="width:75%">工程ID:{{$route.query.prjid}}</span>
          <span :title="$route.query.name" class="projectName">工程名称:{{$route.query.name}}</span>
        </div>
        <Row>
          <Col span="18">
            <Form ref="formValidate" :model="formValidate" :label-width="80" style="width:80%">
                    <div  v-for="(item, index) in formValidate.items"
                          :key="index" class="codeItem">
                    <FormItem 
                          v-if="item.status"
                          label="事件名称"
                          :prop="'items.' + index + '.name'"
                          :rules="{required: true, message: '事件名称不能为空', trigger: 'blur'}">
                      <Row>
                          <Col span="18">
                              <Input type="text" v-model="item.name" placeholder="输入事件名称"></Input>
                          </Col>
                      </Row>
                  </FormItem>
                  <FormItem
                          label="事件指令"
                          v-if="item.status"
                          :prop="'items.' + index + '.content'"
                          :rules="[
                            {required: true, message: '事件指令不能为空', trigger: 'blur'},
                            {validator:jsonFN,trigger:'blur'}
                        ]">
                      <Row>
                          <Col span="18">
                              <Input type="textarea" v-model="item.content" :autosize="{minRows: 2,maxRows: 15}" placeholder="输入json字符串格式的事件指令"></Input>
                          </Col>
                          <Col span="4" offset="1" style="position: absolute;right:0;bottom: 0;">
                            <Button type="primary"  @click="sendMesssageFn(item)" style="margin-bottom:14px">发送指令</Button>
                            <Poptip
                                confirm
                                title="确定要删除吗?"
                                @on-ok="delItems(item)"
                                >
                                <Button type="error">删除指令</Button>
                            </Poptip>
                            
                          </Col>
                      </Row>
                  </FormItem>
                </div>
                <FormItem>
                      <Row>
                          <Col span="12">
                            <Button @click="addItems()" icon="md-add">增加指令</Button>
                            <Tooltip class="too" style="margin-left: 10px;" :transfer='true' max-width="240" content="如还需从文件中导入指令，请先从文件中导入再添加" placement="top">
                              <Icon type="ios-alert" class="ios-alert" />
                            </Tooltip>
                          </Col>
                      </Row>
                  </FormItem>
              </Form>
          </Col>
          <Col span="4">
             <Upload  
                :before-upload="getFileContent"
                :show-upload-list="false"
                action="//jsonplaceholder.typicode.com/posts/">
               <Button>从文件中导入</Button>
               <Tooltip class="too" style="margin-left: 10px;" :transfer='true' max-width="240" content="请导入txt或json格式文件,为防止中文乱码，文件保存时请以utf-8格式保存" placement="top">
                  <Icon type="ios-alert" class="ios-alert" />
               </Tooltip>
               <div v-if="showFileError" style="color:red">请导入json或txt格式文件</div>
             </Upload>
            <Button style="margin-top:14px" @click="exportFile">导出到文件</Button>
          </Col>
        </Row>
    </Modal>
  </div>
</template>
<script>
import {allNodeInfo,triggerEffect} from '@/api/drill_compete.js'
import moment from 'moment'
export default {
  name:'cusdomEffect',
  data(){
    return{
      effectModel:false,
      load:true,
      showFileError:false,
      formValidate: {
        items:[
          {
            name: '',
            index: 0,
            content:'',
            status:true
          },
        ]
      },
    }
  },
  methods:{
    openModal(){
      this.initFormData()
      this.effectModel = true;
    },
    //删除指令
    delItems(item){
      if(this.formValidate.items.filter(f=>f.status).length==1){
        this.$Message.info('只有最后一条指令,无法删除!');
        return;
      }
      this.formValidate.items[item.index].status = false;
    },
    //添加指令
    addItems(){
      let len = this.formValidate.items.length;
      this.formValidate.items.push({
            name: '',
            index: len,
            content:'',
            status:true
          })
    },
    //发送数据函数
    sendMesssageFn(item){
      if(item.name&&item.content){
        try{
          const a = JSON.parse(item.content);
          console.log(a);
          triggerEffect(this.$route.query.prjid,item.content).then(res=>{
          if(res.code==1){
            this.$Message.info('发送信息成功');
          }else{
            this.$Message.error(res.message);
          }   
        })
        }catch(err){
          const str = 'items.' + item.index + '.content'
          this.$refs.formValidate.validateField(str)
        }
      }else{
        const str = 'items.' + item.index + '.content';
        const strName = 'items.' + item.index + '.name'
        this.$refs.formValidate.validateField(strName);
        this.$refs.formValidate.validateField(str)
      }
    },
    cancel(){
      this.effectModel = false;
    },
    setModalLoading(){
      this.load = false;
      this.$nextTick(()=>{
        this.load = true;//下次点击可以继续展示加载状态
      })
    },
    jsonFN(rule, value, callback){
      if(value){
        try{
          const a = JSON.parse(value);
          callback()
        }catch(err){
          callback(new Error('请输入json格式的字符串'))
        }
      }else{
        callback(new Error('指令不能为空'))
      }
    },
    initFormData(){
      this.formValidate = {
        items:[
          {
            name:'',
            content:'',
            index:0,
            status:true
          }
        ]
      };
      this.showFileError = false;
      this.$refs.formValidate.resetFields();
    },
    getFileContent(file){
      if(!(file.name.endsWith('.txt')||file.name.endsWith('.json'))){
        this.showFileError = true;
        return false;
      }
      this.showFileError = false;
      let _this = this;
      const reader = new FileReader();
      reader.readAsText(file,"UTF-8")
      reader.onload = function(e){
        const fileString = e.target.result;
        const myData = JSON.parse(fileString);
        const formData = myData.map((item,index)=>{
          const obj = {};
          obj.index = index;
          obj.name = item.name;
          obj.status = true;
          delete item.name;
          obj.content = JSON.stringify(item);
          return obj;
        }) 
       _this.$set(_this.formValidate,'items',formData);
       _this.$nextTick(()=>{
        _this.formValidate.items.forEach(item=>{
          const str = 'items.' + item.index + '.content';
          const strName = 'items.' + item.index + '.name'
          _this.$refs.formValidate.validateField(strName);
          _this.$refs.formValidate.validateField(str)
       })
       })
      }
      return false;
    },
    exportFile(){
      const data = this.formValidate.items.filter(f=>f.status).map(item=>{
        let obj = {};
        obj.name = item.name;
        const content = JSON.parse(item.content);
        obj = {...obj,...content}
        return obj;
      })
      let dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
      let downloadAnchorNode = document.createElement('a')
      downloadAnchorNode.setAttribute("href", dataStr);
      downloadAnchorNode.setAttribute("download", `${this.$route.query.name}.json`)
      downloadAnchorNode.click();
      downloadAnchorNode.remove();
    }
  },
  mounted(){
   
  }
}
</script>
<style scoped>
.title{
    font-size: 14px;
    margin-bottom: 14px;
    display: flex;
    justify-content: space-between;
    font-weight: 600;
}
.codeItem{
  position: relative;padding-top: 18px;border-top: 1px dashed #aaa;
}
.codeForm  div.codeItem:first-child{
  padding-top: 0px;border-top: none;
}
.projectName{
  width:25%;
  overflow:hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
.ios-alert {
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
</style>